<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <!-- <el-form-item label="项目名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="模块" prop="category_id">
          <el-cascader
            v-model="formInline.category_id"
            :options="options3"
            :props="{
              label: 'name',
              value: 'id',
              checkStrictly: true,
              emitPath: false,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="时间">
          <el-date-picker v-model="formInline.value" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        max-height="600"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" align="center" label="ID" width="70">
        </el-table-column>
        <el-table-column prop="level3_name" align="center" label="模块">
        </el-table-column>
        <el-table-column prop="image" align="center" label="图片">
          <template slot-scope="scope">
            <div @click="handlehover(scope.row)">
              <el-image
                style="width: 50px; height: 50px"
                :src="imgHeader + scope.row.img"
                fit="cover"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" align="center" label="创建时间">
        </el-table-column>
        <el-table-column prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
              @change="ifLook(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="sanChu(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 100, 200, 300]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
      :title="titleText"
      ref="form"
    >
      <el-form
        :model="formLabelAlign"
        label-width="70px"
        ref="form"
        :rules="rules"
      >
        <div class="oneLine">
          <el-form-item label="模块" prop="category_id">
            <el-cascader
              v-model="formLabelAlign.category_id"
              :options="options3"
              :props="{
                label: 'name',
                value: 'id',
                checkStrictly: true,
                emitPath: false,
              }"
              clearable
            ></el-cascader>
          </el-form-item>
        </div>
        <!-- <div class="oneLine">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="formLabelAlign.sort"
              placeholder="请序号"
            ></el-input>
          </el-form-item>
        </div> -->

        <div class="oneLine">
          <el-form-item label="上传图片">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFiles"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
              multiple
              :on-change="fileChange"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
            <ul class="el-upload-list el-upload-list--picture-card">
              <draggable v-model="imgShowList" class="imageBox">
                <div
                  v-for="(item, index) in imgShowList"
                  :key="index"
                  id="liBox"
                >
                  <li class="el-upload-list__item is-success animated">
                    <img
                      :src="imgHeader + item"
                      alt=""
                      class="el-upload-list__item-thumbnail"
                    />
                    <i class="el-icon-close"></i>
                    <span class="el-upload-list__item-actions">
                      <!-- 预览 -->
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreviewFileDetail(item)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <!-- 删除 -->
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemoveFileDetail(index)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </li>
                  <el-form-item label="选择排序" class="sortBox">
                    <el-input
                      v-model="desc[index].sort"
                      style="width: 80px"
                    ></el-input>
                  </el-form-item>
                </div>
              </draggable>
            </ul>
            <!-- <el-image
              v-for="(item1, index1) in imgShowList"
              :key="index1"
              class="imageGood"
              :src="'https://bjsf.bjsky.top/'+item1"
              style="width: 180px; height: 120px"
            ></el-image> -->
          </el-form-item>
        </div>
      </el-form>
      <div class="btnBox">
        <el-button type="primary" dialogVisible class="confirm" @click="save"
          >确 认</el-button
        >
        <el-button
          type="primary"
          dialogVisible
          class="confirm"
          @click="submitData()"
          >返 回</el-button
        >
      </div>
    </el-dialog>
    <!-- 预览弹出层 -->
    <el-dialog :visible.sync="dialogVisibleDetail" class="imageDia">
      <el-image :src="imgHeader + dialogImageDetailUrl"></el-image>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleImg" width="40%" center>
      <div class="imgDialogBox">
        <div v-for="(item, index) in imgDialogList" :key="index">
          <el-image
            :src="imgHeader + item"
            style="width: 140px; height: 100px"
            fit="cover"
          ></el-image>
        </div>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import draggable from "vuedraggable";
import { opinions, uploadFiles, genreList } from "../../../../utils/api";
import {
  getCarouselChart,
  addCarouselChart,
  editCarouselChart,
  upCarouselChart,
  delCarouselChart,
} from "../../../../utils/main";
import { compressImage } from "../../../../assets/js/compressImage";
export default {
  components: {
    draggable,
  },
  data() {
    return {
      imgHeader: this.Global.imgHeader,

      options: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "2",
          label: "否",
        },
      ],
      options3: [],
      formLabelAlign: {
        id: "",
        category_id: "",
        avatar: "",
      },
      fileLimit: 1,
      //   上传图片
      fileList: [],
      dialogImageDetailUrl: "",
      dialogVisibleDetail: false,
      dialogVisibleImg: false,
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      loading: false,
      token: sessionStorage.getItem("token"),
      dialogVisible: false,
      formInline: {
        category_id: "",
        name: "",
      },
      tableData: [],
      parameter: {
        common: "",
      },
      total: 0,
      limit: 10,
      page: 1,
      name: "",
      status: "",
      currentPage: 1,
      type: 2,
      imageUrl: "",
      imageUrl1: "",
      titleText: "",
      parent_id: "0",
      status: "",
      value: "",
      imgShowList: [],
      desc: [{ img: "", sort: "" }],
      fileType: ["png", "jpg", "jpeg"],
      imgDialogList: [],
      rules: {
        category_id: [
          { required: true, message: "请选择模块", trigger: "change" },
        ],
        sort: [
          {
            validator: (rule, value, callback) => {
              var reg = /^(0|[1-9]\d*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0的整数"));
              }
              if (value > 999999999) {
                callback(new Error("不能大于999999999"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handlehover(row) {
      console.log("mmm");
      this.imgDialogList = [];
      row.desc.forEach((item) => {
        this.imgDialogList.push(item.img);
      });
      this.dialogVisibleImg = true;
    },
    genreLists() {
      genreList(this.token)
        .then((res) => {
          if (res.data.status) {
            this.options3 = res.data.data;
            this.options3 = this.options3.filter(function (item) {
              return item.id != 234 && item.id != 35;
            });
            this.options3.forEach((item) => {
              if (item.children) {
                item.children.forEach((i) => {
                  if (i.children) {
                    delete i.children;
                  }
                });
              }
            });
            console.log("pp", this.options3);
            let timer = setTimeout(() => {
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    ifLook(row) {
      // console.log(row.status);
      upCarouselChart(this.token, row.id, row.status).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          // this.getList();
        }
      });
    },
    // 返回
    submitData() {
      this.$refs.form.resetFields();
      this.formLabelAlign = {};
      this.imgShowList = [];
      this.desc = [{ img: "", sort: "" }];
      this.dialogVisible = false;
    },
    //查询
    onSubmit() {
      // this.opinionsS();
      // this.name = this.formInline.name;
      // this.status = this.formInline.status;
      this.page = 1;
      this.getList();
    },
    handleReset() {
      // this.name = "";
      // this.status = "";
      // this.formInline.name = "";
      // this.formInline.status = "";
      this.formInline.category_id = "";
      this.getList();
    },
    //序号
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    //关闭
    handleClose(done) {
      this.$refs.form.resetFields();
      this.imageUrl = "";
      this.formLabelAlign = {};
      this.imgShowList = [];
      this.desc = [{ img: "", sort: "" }];
      done();
      // this.$refs[formName].resetFields();
    },
    //条数
    handleSizeChange(val) {
      this.limit = val;
      // this.opinionsS();
      this.getList();
    },
    //页数
    handleCurrentChange(val) {
      this.page = val;
      // this.opinionsS();
      this.getList();
    },
    // 新增
    handleAdd() {
      this.formLabelAlign = {};
      this.imgShowList = [];
      this.desc = [{ img: "", sort: "" }];
      this.imageUrl = "";
      this.dialogVisible = true;
      this.titleText = "新增";
    },
    // 编辑
    handleEdit(row) {
      let obj = JSON.parse(JSON.stringify(row));
      // console.log("obj", JSON.parse(obj.decc));
      this.formLabelAlign.id = obj.id;
      this.formLabelAlign.category_id = obj.level3;
      this.desc = obj.desc;
      this.imgShowList = [];
      this.desc.forEach((item) => {
        this.imgShowList.push(item.img);
      });
      // this.imageUrl = "https://bjsf.bjsky.top/" + obj.image;
      this.dialogVisible = true;
      this.titleText = "编辑";
      if (obj.status == 1) {
        this.dialogVisible = false;
        this.$message({
          type: "warning",
          message: "上架状态下不能编辑",
        });
      }
    },
    //确定添加
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.imgShowList.forEach((item, index) => {
            this.desc[index].img = item;
            this.desc[index].sort = this.desc[index].sort;
          });
          console.log("111", this.imgShowList);
          console.log("222", this.desc);
          // return;
          // console.log(this.formLabelAlign, "8888880");
          if (this.formLabelAlign.id != null) {
            // console.log(this.formLabelAlign, "000");
            // 编辑
            editCarouselChart(
              this.token,
              this.formLabelAlign.id,
              this.formLabelAlign.category_id,
              JSON.stringify(this.desc)
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            // 新增
            addCarouselChart(
              this.token,
              this.formLabelAlign.category_id,
              JSON.stringify(this.desc)
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "新增成功",
                });
                this.total = res.data.data.total;
                this.formLabelAlign = {};
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除
    sanChu(row) {
      if (row.status == 1) {
        this.dialogVisible = false;
        this.$message({
          type: "warning",
          message: "上架状态下不能删除",
        });
        return;
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(row.id);
          delCarouselChart(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增
    handleRemove() {},
    handlePictureCardPreviewFileDetail(file) {
      this.dialogImageDetailUrl = file;
      this.dialogVisibleDetail = true;
    },
    // 删除
    handleRemoveFileDetail(index) {
      this.imgShowList.splice(index, 1);
      this.desc.splice(index, 1);
      this.fileList.splice(index, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        // 如果文件类型不在允许上传的范围内;
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    //上传成功后的回调
    handleSuccess(i) {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      // this.handleClose();
      this.fileList.splice(i, 1); //删除上传的文件
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },

    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFiles(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.imgShowList.push(res.data.data.saveurl);
            this.desc.push({ img: "", sort: "" });
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFiles(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.imgShowList.push(res.data.data.saveurl);
      //     this.desc.push({ img: "", sort: "" });
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     // let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //     console.log("图片");
      //   }
      // });
    },
    // 获取列表
    async getList() {
      this.loading = true;
      let res = await getCarouselChart(
        this.token,
        this.formInline.category_id,
        this.page,
        this.limit
      );
      if (res.data.status) {
        this.tableData = res.data.data.data || [];
        this.total = res.data.data.total;
        this.tableData.forEach((item) => {
          if (item.desc.length > 0) {
            item.img = item.desc[0].img;
          }
        });
        let timer = setTimeout(() => {
          this.loading = false;
          clearTimeout(timer);
        }, 400);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    //列表数据
    // opinionsS() {
    //   this.loading = true;
    //   opinions(
    //     this.token,
    //     this.page,
    //     this.limit,
    //     this.value,
    //     this.formInline.mobile,
    //     this.formInline.name
    //   )
    //     .then((res) => {
    //       if (res.data.status) {
    //         this.tableData = res.data.data.data;
    //         this.total = res.data.data.count;
    //         this.tableData.forEach((item) => {
    //           if (item.avatar) {
    //             item.image = item.avatar;
    //             item.img = "https://bjsf.bjsky.top" + item.avatar;
    //           }
    //           if (item.ctime) {
    //             item.ctime_text = this.getNowTime(item.ctime * 1000);
    //           }
    //         });
    //         let timer = setTimeout(() => {
    //           this.loading = false;
    //           clearTimeout(timer);
    //         }, 400);
    //       } else {
    //         if (res.data.msg == "token失效,请重新进行登录") {
    //           this.$router.push("/login");
    //         }
    //         if (res.data.msg == "此账号没有权限") {
    //           this.$message.error(res.data.msg);
    //           this.loading = false;
    //         }
    //         let timer = setTimeout(() => {
    //           this.$message.error(res.data.msg);
    //         }, 5000);
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err.message);
    //     });
    // },
    // getNowTime(e) {
    //   let date = new Date(e);
    //   let year = date.getFullYear();
    //   let month = date.getMonth() + 1;
    //   let day = date.getDate();
    //   let hour = date.getHours();
    //   let minute = date.getMinutes();
    //   month = month < 10 ? "0" + month : month;
    //   day = day < 10 ? "0" + day : day;
    //   hour = hour < 10 ? "0" + hour : hour;
    //   minute = minute < 10 ? "0" + minute : minute;
    //   return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    // },
  },
  mounted() {
    // this.opinionsS();
    this.getList();
    this.genreLists();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.divFlex {
  display: flex;
  align-items: center;
}
.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
  flex-flow: row wrap;
}
.addP {
  font-size: 22px;
  text-align: center;
  margin-bottom: 10px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.btnBox {
  display: flex;
  justify-content: center;
}
.imageBox {
  /* widows: 90%; */
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
#liBox {
  margin-right: 12px;
}
.sortBox {
  margin-bottom: 20px;
}
.imgDialogBox {
  display: flex;
  flex-wrap: wrap;
  /* border: 1px solid red; */
}
.imgDialogBox .el-image {
  margin-right: 10px;
}
</style>